package com.syl.auth.authentication;

import com.syl.auth.config.SmallSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SmallAccessDecisionManager
 * @Description 鉴权决策管理器
 * @Author YunLong
 * @Date 2023/4/26 21:36
 */
@Slf4j
@Component
public class SmallAccessDecisionManager implements AccessDecisionManager {

    @Resource
    SmallSecurityProperties smallSecurityProperties;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        // 获取当前请求的url
        HttpServletRequest request = ((FilterInvocation) object).getRequest();
        String url = request.getRequestURL().toString();
        List<String> notLoginUrls = smallSecurityProperties.getNotLoginUrls();
        // 如果是不需要登录就能访问的接口，直接放行
        if (!CollectionUtils.isEmpty(notLoginUrls) && notLoginUrls.contains(url)) {
            return;
        }
        // 获取用户拥有的权限（角色）信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        // 这里判断用户拥有的角色和该url需要的角色是否有匹配
        for (ConfigAttribute configAttribute : collection) {
            String attribute = configAttribute.getAttribute();
            boolean contains = roles.contains(attribute);
            if (contains) {
                log.debug("当前用户包含当前角色");
                return;
            }

            /*
            for (GrantedAuthority authority : authorities) {
                if (attribute.equals(authority.getAuthority())) {
                    log.debug("角色匹配成功,本次鉴权成功。角色:{}", authority.getAuthority());
                    return;
                }
            }
            */
        }
        // 没有匹配就抛出异常
        throw new AccessDeniedException("权限不足,无法访问");

    }

    // 此 AccessDecisionManager 实现是否可以处理传递的 ConfigAttribute
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    // 此 AccessDecisionManager 实现是否能够提供该对象类型的访问控制决策。
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
